<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\Payload;

class AuthCheck
{
    public function handle($request, Closure $next)
    {
        $auth = JWTAuth::parseToken();
        $payload = $auth->getPayload();
        $tokenExpired = $payload->get('exp');
        //  本应用 auth token 失效都要刷新 token
        if ($tokenExpired < time() - 3600) {
            try {
                $token = $auth->refresh();
            } catch (JWTException $e) {
                throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
            }
            $response = $next($request);
            $response->headers->set('Authorization', 'Bearer ' . $token);
            return $response;
        }
        return $next($request);
    }
}
